package com.qd.panda.service.stroke.order;

import cn.hutool.core.math.Money;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.excel.ExcelExport;
import com.cdqidi.excel.util.ExportPage;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.JacksonUtil;
import com.cdqidi.util.RedisTemplateUtil;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.qd.common.panda.constant.PandaConstant;
import com.qd.common.panda.domain.entity.order.OrderStatisticsDTO;
import com.qd.common.panda.domain.entity.stroke.preferential.*;
import com.qd.panda.mapper.stroke.UserStrokeOrderPreferentialLogMapper;
import com.qd.panda.model.UserStrokeOrderPreferentialLog;
import com.qd.panda.service.stroke.BigDecimalUtil;
import com.qd.panda.service.stroke.DisplayUtil;
import com.qd.system.service.dict.MbUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * 优惠记录
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class UserStrokeOrderPreferentialLogService extends BaseService<UserStrokeOrderPreferentialLogMapper, UserStrokeOrderPreferentialLog> {

    private static final String PREFIX_ID = "panda_user_stroke_order_preferential_log_logId_{0}";
    private static final String PREFIX_LIST_ORDER_ID = "panda_user_stroke_order_preferential_log_List_order_id_{0}";

    private final RedisTemplateUtil<UserStrokeOrderPreferentialLog> redisTemplateUtil;

    private final HttpServletResponse response;


    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserStrokeOrderPreferentialLogDTO save(UserStrokeOrderPreferentialLogDTO dto) {
        final UserStrokeOrderPreferentialLog model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserStrokeOrderPreferentialLogDTO update(UserStrokeOrderPreferentialLogDTO dto) {
        final UserStrokeOrderPreferentialLog historyModel = Optional.ofNullable(getById(dto.getLogId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final UserStrokeOrderPreferentialLog model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 批量添加
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<UserStrokeOrderPreferentialLog> mList) {
        try {
            if (!super.saveBatch(mList)) {
                throw new ApiException("批量添加失败");
            }
        } finally {
            clearCaches(mList);
        }
    }

    /**
     * 批量更新
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateBatchIds(List<UserStrokeOrderPreferentialLog> mList) {
        final List<String> ids = mList.stream().map(UserStrokeOrderPreferentialLog::getLogId).collect(toList());
        final List<UserStrokeOrderPreferentialLog> historyModelList = checkIds(ids);
        try {
            if (!super.updateBatchById(mList)) {
                throw new ApiException("批量更新失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
            ids.clear();
        }
    }

    /**
     * 删除，单个
     *
     * @param logId 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String logId) {
        final UserStrokeOrderPreferentialLog historyModel = Optional.ofNullable(getById(logId)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(logId)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        final List<UserStrokeOrderPreferentialLog> historyModelList = checkIds(ids);
        try {
            if (!super.removeByIds(ids)) {
                throw new ApiException("批量删除失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(UserStrokeOrderPreferentialLogDTO dto) {
        final QueryWrapper<UserStrokeOrderPreferentialLog> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param logId 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String logId) {
        boolean exists = false;
        if (StringUtils.hasLength(logId)) {
            final UserStrokeOrderPreferentialLog model = getById(logId);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param logId 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public UserStrokeOrderPreferentialLog getById(String logId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, logId);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(logId), UserStrokeOrderPreferentialLog.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param logId 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserStrokeOrderPreferentialLogDTO getByIdDto(String logId) {
        return Optional.ofNullable(getById(logId)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public UserStrokeOrderPreferentialLog getOne(UserStrokeOrderPreferentialLogDTO dto) {
        final QueryWrapper<UserStrokeOrderPreferentialLog> queryWrapper = createQueryWrapper(dto);
        UserStrokeOrderPreferentialLog model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserStrokeOrderPreferentialLogDTO getOneDto(UserStrokeOrderPreferentialLogDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<UserStrokeOrderPreferentialLog> getList(UserStrokeOrderPreferentialLogDTO dto) {
        final QueryWrapper<UserStrokeOrderPreferentialLog> queryWrapper = createQueryWrapper(dto);
        final List<UserStrokeOrderPreferentialLog> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<UserStrokeOrderPreferentialLogDTO> getListDto(UserStrokeOrderPreferentialLogDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<UserStrokeOrderPreferentialLogDTO> page(Page<UserStrokeOrderPreferentialLog> page, UserStrokeOrderPreferentialLogDTO dto) {
        final QueryWrapper<UserStrokeOrderPreferentialLog> queryWrapper = createQueryWrapper(dto, "t1.");
        final IPage<UserStrokeOrderPreferentialLogDTO> iPage = baseMapper.page(page, queryWrapper);
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<UserStrokeOrderPreferentialLogDisplayDTO> pageOrderPreferentialLogDisplay(Page<UserStrokeOrderPreferentialLogDisplayDTO> page, UserStrokeOrderPreferentialLogQueryDTO dto) {
        final QueryWrapper<UserStrokeOrderPreferentialLogQueryDTO> queryWrapper = createQueryWrapper(dto);
        queryWrapper.orderByAsc("t1.platform");
        queryWrapper.orderByDesc("t2.start_time");
        queryWrapper.orderByDesc("t2.pay_status");
        final IPage<UserStrokeOrderPreferentialLogDisplayDTO> iPage = baseMapper.pageOrderPreferentialLogDisplay(page, queryWrapper);
        Optional.ofNullable(iPage.getRecords()).ifPresent(l -> l.forEach(this::buildDisplay));
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<AppUserStrokeOrderPreferentialLogDisplayDTO> appPageUserStrokeOrderPreferentialLog(Page<AppUserStrokeOrderPreferentialLogDisplayDTO> page, AppUserStrokeOrderPreferentialLogQueryDTO dto) {
        final QueryWrapper<AppUserStrokeOrderPreferentialLogQueryDTO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("t2.pay_status", DisplayUtil.PAY_STATUS_1);
        if (null != dto.getTripType()) {
            queryWrapper.eq("t2.trip_type", dto.getTripType());
        }
        if (null != dto.getPreferentialCategory()) {
            queryWrapper.eq("t1.preferential_category", dto.getPreferentialCategory());
        }
        if (StringUtils.hasLength(dto.getUserId())) {
            queryWrapper.eq("t2.user_id", dto.getUserId());
        }
        if (StringUtils.hasLength(dto.getBeginTime())) {
            queryWrapper.apply("date_format(t1.add_time,'%Y-%m-%d') >= {0}", dto.getBeginTime());
        }
        if (StringUtils.hasLength(dto.getEndTime())) {
            queryWrapper.apply("date_format(t1.add_time,'%Y-%m-%d') <= {0}", dto.getEndTime());
        }
        queryWrapper.orderByDesc("t1.add_time");
        final IPage<AppUserStrokeOrderPreferentialLogDisplayDTO> iPage = baseMapper.appPageUserStrokeOrderPreferentialLog(page, queryWrapper);
        Optional.ofNullable(iPage.getRecords()).ifPresent(l -> l.forEach(this::buildDisplay));
        queryWrapper.clear();
        return iPage;
    }

    private void buildDisplay(AppUserStrokeOrderPreferentialLogDisplayDTO dto) {
        dto.setPriceDisplay(Optional.ofNullable(dto.getPrice()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setDiscountAmountDisplay(Optional.ofNullable(dto.getDiscountAmount()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setServiceChargeDisplay(Optional.ofNullable(dto.getServiceCharge()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setTripTypeDisplay(DisplayUtil.getTripTypeDisplay(dto.getTripType()));
        dto.setPreferentialCategoryDisplay(MbUtil.idToDisplay(dto.getPreferentialCategory()));
        if (null != dto.getTripType()) {
            ObjectNode objectNode = JacksonUtil.getObjectMapper().createObjectNode();
            if (dto.getTripType().equals(DisplayUtil.TRIP_TYPE_2)) {
                //加油
            }
        }
    }

    /**
     * 导出Excel
     *
     * @param query 查询条件
     */
    @Transactional(readOnly = true)
    public void export(UserStrokeOrderPreferentialLogQueryDTO query) {
        final ExportPage<UserStrokeOrderPreferentialLogDisplayDTO, UserStrokeOrderPreferentialLogDisplayDTO> exportPage = new ExportPage<>();
        try {
            final List<UserStrokeOrderPreferentialLogDisplayDTO> list = exportPage.getAllForPage(page -> pageOrderPreferentialLogDisplay(page, query).getRecords());
            try {
                ExcelExport.downloadExcel(response, UserStrokeOrderPreferentialLogDisplayDTO.class, () -> list);
            } catch (IOException e) {
                log.error("导出失败", e);
                throw new ApiException("导出失败");
            }
        } finally {
            exportPage.freeData();
        }
    }

    /**
     * 详情
     *
     * @param logId 日志ID
     * @return 详细信息
     */
    @Transactional(readOnly = true)
    public UserStrokeOrderPreferentialLogDisplayDTO getOrderPreferentialLogByLogId(String logId) {
        UserStrokeOrderPreferentialLogDisplayDTO orderPreferentialLogDisplayDTO = baseMapper.getOrderPreferentialLogByLogId(logId);
        Optional.ofNullable(orderPreferentialLogDisplayDTO).ifPresent(this::buildDisplay);
        return orderPreferentialLogDisplayDTO;
    }

    private void buildDisplay(UserStrokeOrderPreferentialLogDisplayDTO dto) {
        dto.setPriceDisplay(Optional.ofNullable(dto.getPrice()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setDiscountAmountDisplay(Optional.ofNullable(dto.getDiscountAmount()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setServiceChargeDisplay(Optional.ofNullable(dto.getServiceCharge()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setPayStatusDisplay(DisplayUtil.getPayStatusDisplay(dto.getPayStatus()));
        dto.setTripTypeDisplay(DisplayUtil.getTripTypeDisplay(dto.getTripType()));
        dto.setPlatformDisplay(PandaConstant.getPlatformDisplay(dto.getPlatform()));
        dto.setPayAmount(new Money(dto.getPrice()).subtract(new Money(dto.getDiscountAmount())).getAmount());
        dto.setPayAmountDisplay(Optional.ofNullable(dto.getPayAmount()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(UserStrokeOrderPreferentialLog model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getLogId()));
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_LIST_ORDER_ID, model.getOrderId()));
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<UserStrokeOrderPreferentialLog> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        List<String> ids = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getLogId())).collect(toList());
        if (!ids.isEmpty()) {
            redisTemplateUtil.deleteByKey(ids);
            ids.clear();
        }
        Set<String> orderIds = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_LIST_ORDER_ID, model.getOrderId())).collect(Collectors.toSet());
        if (!orderIds.isEmpty()) {
            redisTemplateUtil.deleteByKey(orderIds);
            orderIds.clear();
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public UserStrokeOrderPreferentialLogDTO modelToDto(UserStrokeOrderPreferentialLog model) {
        if (null == model) {
            return null;
        }
        final UserStrokeOrderPreferentialLogDTO dto = new UserStrokeOrderPreferentialLogDTO();
        dto.setLogId(model.getLogId());
        dto.setThirdPartyOrderId(model.getThirdPartyOrderId());
        dto.setPrice(model.getPrice());
        dto.setCustomerDiscount(model.getCustomerDiscount());
        dto.setDiscountAmount(model.getDiscountAmount());
        dto.setAddTime(model.getAddTime());
        dto.setPlatform(model.getPlatform());
        dto.setIdx(model.getIdx());
        dto.setOrderId(model.getOrderId());
        dto.setSid(model.getSid());
        dto.setPreferentialCategory(model.getPreferentialCategory());
        dto.setFlag(model.getFlag());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public UserStrokeOrderPreferentialLog dtoToModel(UserStrokeOrderPreferentialLogDTO dto) {
        if (null == dto) {
            return null;
        }
        final UserStrokeOrderPreferentialLog model = new UserStrokeOrderPreferentialLog();
        model.setLogId(dto.getLogId());
        model.setThirdPartyOrderId(dto.getThirdPartyOrderId());
        model.setPrice(dto.getPrice());
        model.setCustomerDiscount(dto.getCustomerDiscount());
        model.setDiscountAmount(dto.getDiscountAmount());
        model.setAddTime(dto.getAddTime());
        model.setPlatform(dto.getPlatform());
        model.setIdx(dto.getIdx());
        model.setOrderId(dto.getOrderId());
        model.setSid(dto.getSid());
        model.setPreferentialCategory(dto.getPreferentialCategory());
        model.setFlag(dto.getFlag());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(UserStrokeOrderPreferentialLogDTO dto) {
        dto.setPreferentialCategoryDisplay(MbUtil.idToDisplay(dto.getPreferentialCategory()));
        dto.setPriceDisplay(Optional.ofNullable(dto.getPrice()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setDiscountAmountDisplay(Optional.ofNullable(dto.getDiscountAmount()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setPlatformDisplay(PandaConstant.getPlatformDisplay(dto.getPlatform()));
        if (null == dto.getServiceCharge()) {
            dto.setServiceCharge(new BigDecimal("0"));
        }
        dto.setServiceChargeDisplay(Optional.ofNullable(dto.getServiceCharge()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        if(null !=dto.getFlag()){
            if(dto.getFlag().equals(0)){
                dto.setFlagDisplay("实际优惠");
            }
            if (dto.getFlag().equals(1)) {
                dto.setFlagDisplay("对账");
            }
        }
    }

    @Transactional(readOnly = true)
    public List<UserStrokeOrderPreferentialLogDTO> getCategoryListByOrderId(String orderId) {
        return getCategoryListByOrderId(orderId, null);
    }

    @Transactional(readOnly = true)
    public List<UserStrokeOrderPreferentialLogDTO> getCategoryListByOrderId(String orderId, Integer flag) {
        final QueryWrapper<UserStrokeOrderPreferentialLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        queryWrapper.orderByAsc("idx");
        final List<UserStrokeOrderPreferentialLog> list = redisTemplateUtil.getList(new CacheKey().setKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_LIST_ORDER_ID, orderId)), () -> getBaseMapper().selectList(queryWrapper), UserStrokeOrderPreferentialLog.class);
        if (list.isEmpty()) {
            return Collections.emptyList();
        }
        List<UserStrokeOrderPreferentialLogDTO> dtoList = modelToDtoList(list);
        if(null !=flag){
            return dtoList.stream().filter(u->u.getFlag().equals(flag)).collect(toList());
        }
        return dtoList;
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<UserStrokeOrderPreferentialLogDTO> modelToDtoList(List<UserStrokeOrderPreferentialLog> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<UserStrokeOrderPreferentialLog> dtoToModelList(List<UserStrokeOrderPreferentialLogDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<UserStrokeOrderPreferentialLog> createQueryWrapper(UserStrokeOrderPreferentialLogDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<UserStrokeOrderPreferentialLog> createQueryWrapper(UserStrokeOrderPreferentialLogDTO dto, String tableAlias) {
        final QueryWrapper<UserStrokeOrderPreferentialLog> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(dto.getThirdPartyOrderId())) {
                queryWrapper.eq(tableAlias + "third_party_order_id", dto.getThirdPartyOrderId());
            }
            if (StringUtils.hasLength(dto.getOrderId())) {
                queryWrapper.eq(tableAlias + "order_id", dto.getOrderId());
            }
            if (StringUtils.hasLength(dto.getSid())) {
                queryWrapper.eq(tableAlias + "sid", dto.getSid());
            }
            if (StringUtils.hasLength(dto.getPreferentialCategory())) {
                queryWrapper.eq(tableAlias + "preferential_category", dto.getPreferentialCategory());
            }
        }
        return queryWrapper;
    }

    private QueryWrapper<UserStrokeOrderPreferentialLogQueryDTO> createQueryWrapper(UserStrokeOrderPreferentialLogQueryDTO dto) {
        final QueryWrapper<UserStrokeOrderPreferentialLogQueryDTO> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasLength(dto.getThirdPartyOrderId())) {
            queryWrapper.eq("t1.third_party_order_id", dto.getThirdPartyOrderId());
        }
        if (StringUtils.hasLength(dto.getOrderId())) {
            queryWrapper.eq("t1.order_id", dto.getOrderId());
        }
        if (null != dto.getPayStatus()) {
            queryWrapper.eq("t2.pay_status", dto.getPayStatus());
        }
        if (null != dto.getTripType()) {
            queryWrapper.eq("t2.trip_type", dto.getTripType());
        }
        if (StringUtils.hasLength(dto.getUserId())) {
            queryWrapper.eq("t2.user_id", dto.getUserId());
        }
        if (StringUtils.hasLength(dto.getMobile())) {
            queryWrapper.eq("t3.mobile", dto.getMobile());
        }
        if (StringUtils.hasLength(dto.getPlateNumber())) {
            queryWrapper.eq("t2.plate_number", dto.getPlateNumber());
        }
        if (StringUtils.hasLength(dto.getParkName())) {
            queryWrapper.like("t2.park_name", dto.getParkName());
        }
        if (null != dto.getPlatform()) {
            queryWrapper.eq("t1.platform", dto.getPlatform());
        }
        if (StringUtils.hasLength(dto.getBeginTime())) {
            queryWrapper.apply("date_format(t2.start_time,'%Y-%m-%d') >= {0}", dto.getBeginTime());
        }
        if (StringUtils.hasLength(dto.getEndTime())) {
            queryWrapper.apply("date_format(t2.start_time,'%Y-%m-%d') <= {0}", dto.getEndTime());
        }
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */
    public List<UserStrokeOrderPreferentialLog> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<UserStrokeOrderPreferentialLog> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(UserStrokeOrderPreferentialLog::getLogId).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }


    /**
     * 优惠记录统计
     *
     * @param dto 查询参数
     * @return 订单统计值
     */
    @Transactional(readOnly = true)
    public OrderStatisticsDTO totalOrderStatistics(UserStrokeOrderPreferentialLogQueryDTO dto) {
        final QueryWrapper<UserStrokeOrderPreferentialLogQueryDTO> queryWrapper = createQueryWrapper(dto);
        OrderStatisticsDTO orderStatisticsDTO = getBaseMapper().totalOrderStatistics(queryWrapper, dto.getTripType());
        if (null == orderStatisticsDTO) {
            orderStatisticsDTO = new OrderStatisticsDTO();
        }
        if (null == orderStatisticsDTO.getQuantity()) {
            orderStatisticsDTO.setQuantity(0);
        }
        if (null == orderStatisticsDTO.getOrderAmount()) {
            orderStatisticsDTO.setOrderAmount(new BigDecimal(0));
            orderStatisticsDTO.setPayAmount(new BigDecimal(0));
        } else {
            Money payAmount = new Money(orderStatisticsDTO.getOrderAmount()).subtract(new Money(orderStatisticsDTO.getDiscountAmount()));
            orderStatisticsDTO.setPayAmount(payAmount.getAmount());
        }
        if (null == orderStatisticsDTO.getDiscountAmount()) {
            orderStatisticsDTO.setDiscountAmount(new BigDecimal(0));
        }
        orderStatisticsDTO.setOrderAmountDisplay(BigDecimalUtil.buildDefaultScale(orderStatisticsDTO.getOrderAmount()).stripTrailingZeros().toPlainString());
        orderStatisticsDTO.setPayAmountDisplay(BigDecimalUtil.buildDefaultScale(orderStatisticsDTO.getPayAmount()).stripTrailingZeros().toPlainString());
        orderStatisticsDTO.setDiscountAmountDisplay(BigDecimalUtil.buildDefaultScale(orderStatisticsDTO.getDiscountAmount()).stripTrailingZeros().toPlainString());
        return orderStatisticsDTO;
    }
}